package com.sharemedia.vos
{
	import com.sharemedia.managers.db.TrackDataBase;
	import com.sharemedia.managers.db.UpdateTrackInfoCommand;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.media.ID3Info;
	import flash.media.Sound;
	import flash.net.URLRequest;

	public class ServerTrack extends Track
	{
		public function ServerTrack(uid:String, fileName:String="", path:String="", likeNum:Number=0, unlikeNum:Number=0)
		{
			super(uid, fileName, path, likeNum, unlikeNum);
		}
		
		private var dataBase:TrackDataBase;
		
		public function loadID3(dataBase:TrackDataBase):void
		{
			this.dataBase = dataBase;
			
			var sound:Sound = new Sound();
			sound.load(new URLRequest(path));
			sound.addEventListener(Event.ID3, id3Handler);
			sound.addEventListener(Event.COMPLETE, completeHandler);
			sound.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
		}
		
		protected function id3Handler(event:Event):void
		{
			var id3Info:ID3Info = event.currentTarget.id3;
			var songName:String = (id3Info.songName && id3Info.songName != "") ? id3Info.songName : fileName;
			var artist:String = (id3Info.artist && id3Info.artist != "") ? id3Info.artist : "";
			
			info = new TrackInfo(songName, artist);
			
			updateDB();
		}
		
		protected function errorHandler(event:Event):void
		{
			info = new TrackInfo("undefined", "undefined");
			length = 0;
		}
		
		protected function completeHandler(event:Event):void
		{
			length = event.currentTarget.length;
			updateDB();
		}
		
		protected function updateDB():void
		{
			if(dataBase)
				dataBase.execute(new UpdateTrackInfoCommand(this));
		}
	}
}